#include "subtasks.h"
#include "ui_subtasks.h"
#include <iostream>

SubTasks::SubTasks(QWidget *parent) :
    QWidget(parent),
    uim(new Ui::SubTasks)
{
    uim->setupUi(this);
    SubModel *submodel = new SubModel();
    this->subMod = submodel;
    uim->tableView->setModel(submodel);
    uim->tableView->resizeColumnsToContents();
    uim->tableView->resizeRowsToContents();
}
void SubTasks::update_win()
{
   uim->label_task->setText(this->task_name);

   std::cout<<"qqqqqq   "<<task_num<<std::endl;
   std::cout<<"qqqqqq   "<<this->subMod->task_id<<std::endl;
   this->subMod->task_id = this->task_num;
   this->subMod->refresh();
   uim->tableView->resizeRowsToContents();
    return;
}
SubTasks::~SubTasks()
{
    delete uim;
}

void SubTasks::on_delField_clicked()
{
    QString a = uim->tableView->model()->data(uim->tableView->model()->index(uim->tableView->currentIndex().row(),0)).toString();
    a = a.right(a.length()-1);
    //int b= a.toInt();
    QSqlQuery sql = QSqlQuery();
    sql.prepare("DELETE FROM subtasks s WHERE (s.number = ?) AND (s.id_task = ?)");
    sql.addBindValue(a.toInt());
    sql.addBindValue(this->task_num);
    sql.exec();
    this->subMod->refresh();
    uim->tableView->resizeRowsToContents();
    return;
}

void SubTasks::on_addField_clicked()
{

    QSqlQuery sql = QSqlQuery();
    sql.prepare("insert into subtasks (id_task, subtask, number, time_start, time_end) "
                "VALUES (?, ?, (select s.number from subtasks s where (s.id_task = ? ) "
                "order by s.number desc limit 1), ?,?)");
    sql.addBindValue(this->task_num);
    sql.addBindValue(uim->newSubTask->text());
    sql.addBindValue(this->task_num);
    sql.addBindValue(uim->newStart->text());
    sql.addBindValue(uim->new_finish->text());
    sql.exec();

    this->subMod->refresh();
    uim->tableView->resizeRowsToContents();

    return;

}

void SubTasks::on_retBtn_clicked()
{
    this->hide();
}
